package com.governtalk.backend.controller;

import com.governtalk.backend.dto.AiSolverRequest;
import com.governtalk.backend.dto.AiSolverResponse;
import com.governtalk.backend.dto.ConversationResponse;
import com.governtalk.backend.service.AiSolverService;
import com.governtalk.backend.service.FileUploadService;
import com.governtalk.backend.service.CozeFileUploadService;
import com.governtalk.backend.service.CozeFileRetrieveService;
import com.governtalk.backend.service.CozeChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/api/ai-solver")
public class AiSolverController {

    @Autowired
    private AiSolverService aiSolverService;
    
    @Autowired
    private FileUploadService fileUploadService;
    
    @Autowired
    private CozeFileUploadService cozeFileUploadService;
    
    @Autowired
    private CozeFileRetrieveService cozeFileRetrieveService;
    
    @Autowired
    private CozeChatService cozeChatService;

    @PostMapping("/solve")
    public ResponseEntity<AiSolverResponse> solveQuestion(@RequestBody AiSolverRequest request) {
        try {
            System.out.println("接收到AI解题请求: " + request);
            AiSolverResponse response = aiSolverService.solveQuestion(request);
            System.out.println("AI解题响应: " + response);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("AI解题失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(
                AiSolverResponse.builder()
                    .success(false)
                    .error("服务器内部错误: " + e.getMessage())
                    .build()
            );
        }
    }

    @PostMapping("/solve-with-image")
    public ResponseEntity<AiSolverResponse> solveQuestionWithImage(
            @RequestParam("question") String question,
            @RequestParam(value = "questionType", required = false) String questionType,
            @RequestParam("userId") Long userId,
            @RequestParam("image") MultipartFile image) {
        try {
            // 上传图片文件
            String fileName = fileUploadService.uploadImage(image);
            String imageUrl = fileUploadService.getImageUrl(fileName);

            AiSolverRequest request = AiSolverRequest.builder()
                    .question(question)
                    .questionType(questionType)
                    .userId(userId)
                    .imageUrl(imageUrl)
                    .build();

            System.out.println("接收到AI图片解题请求: " + request + ", 图片: " + image.getOriginalFilename());
            AiSolverResponse response = aiSolverService.solveQuestionWithImage(request, imageUrl);
            System.out.println("AI图片解题响应: " + response);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("AI图片解题失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(
                AiSolverResponse.builder()
                    .success(false)
                    .error("服务器内部错误: " + e.getMessage())
                    .build()
            );
        }
    }

    @GetMapping("/conversation/{userId}")
    public ResponseEntity<ConversationResponse> getUserConversationId(@PathVariable Long userId) {
        try {
            String conversationId = aiSolverService.getUserConversationId(userId);
            return ResponseEntity.ok(ConversationResponse.builder()
                    .userId(userId)
                    .conversationId(conversationId)
                    .build());
        } catch (Exception e) {
            System.err.println("获取用户对话ID失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(
                ConversationResponse.builder()
                    .userId(userId)
                    .conversationId(null)
                    .build()
            );
        }
    }

    @DeleteMapping("/conversation/{userId}")
    public ResponseEntity<Map<String, String>> clearUserConversation(@PathVariable Long userId) {
        try {
            aiSolverService.clearUserConversation(userId);
            Map<String, String> response = new HashMap<>();
            response.put("message", "User conversation history cleared successfully.");
            response.put("userId", userId.toString());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("清除用户对话历史失败: " + e.getMessage());
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "Failed to clear conversation history: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    @PostMapping(value = "/solve-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter solveQuestionStream(@RequestBody AiSolverRequest request) {
        System.out.println("=== 控制器：开始处理AI流式解题请求 ===");
        System.out.println("请求详情: " + request);
        
        SseEmitter emitter = new SseEmitter(30000L); // 30秒超时
        
        CompletableFuture.runAsync(() -> {
            try {
                System.out.println("=== 控制器：异步任务开始执行 ===");
                System.out.println("调用Coze文本对话服务");
                cozeChatService.sendTextChatToCoze(request.getQuestion(), request.getUserId(), emitter);
                System.out.println("=== 控制器：Coze文本对话服务调用完成 ===");
            } catch (Exception e) {
                System.err.println("=== 控制器：AI流式解题异常 ===");
                System.err.println("异常类型: " + e.getClass().getName());
                System.err.println("异常消息: " + e.getMessage());
                System.err.println("异常堆栈: ");
                e.printStackTrace();
                try {
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("AI解析失败: " + e.getMessage()));
                    System.out.println("=== 控制器：错误信息已发送给前端 ===");
                } catch (IOException ioException) {
                    System.err.println("发送错误信息失败: " + ioException.getMessage());
                    ioException.printStackTrace();
                }
                emitter.completeWithError(e);
                System.out.println("=== 控制器：SSE连接已关闭 ===");
            }
        });
        
        System.out.println("=== 控制器：返回SSE Emitter ===");
        return emitter;
    }

    @PostMapping(value = "/solve-with-image-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter solveQuestionWithImageStream(
            @RequestParam("question") String question,
            @RequestParam(value = "questionType", required = false) String questionType,
            @RequestParam("userId") Long userId,
            @RequestParam("image") MultipartFile image) {
        SseEmitter emitter = new SseEmitter(30000L); // 30秒超时
        
        CompletableFuture.runAsync(() -> {
            try {
                System.out.println("=== 开始处理图片解题请求（完整流程） ===");
                System.out.println("问题: " + question);
                System.out.println("用户ID: " + userId);
                System.out.println("图片文件名: " + image.getOriginalFilename());
                System.out.println("图片大小: " + image.getSize() + " 字节");
                
                // 步骤1: 上传图片到Coze平台
                System.out.println("步骤1: 上传图片到Coze平台");
                String fileId = cozeFileUploadService.uploadFileToCoze(image);
                System.out.println("✅ 图片上传成功，文件ID: " + fileId);
                
                // 步骤2: 检索文件内容
                System.out.println("步骤2: 检索文件内容");
                String fileContent = cozeFileRetrieveService.retrieveFileContent(fileId);
                System.out.println("✅ 文件内容检索成功，内容长度: " + fileContent.length());
                
                // 步骤3: 发送基于文件内容的对话请求
                System.out.println("步骤3: 发送基于文件内容的对话请求");
                cozeChatService.sendFileContentChatToCoze(question, fileContent, userId, emitter);
                
            } catch (Exception e) {
                System.err.println("❌ AI流式图片解题失败: " + e.getMessage());
                e.printStackTrace();
                try {
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("AI图片分析失败: " + e.getMessage()));
                } catch (IOException ioException) {
                    System.err.println("发送错误信息失败: " + ioException.getMessage());
                }
                emitter.completeWithError(e);
            }
        });
        
        return emitter;
    }

    /**
     * 完整的文件处理流程API - 上传文件→检索内容→智能体处理→返回结果
     */
    @PostMapping(value = "/process-file-complete", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter processFileComplete(
            @RequestParam("question") String question,
            @RequestParam("userId") Long userId,
            @RequestParam("file") MultipartFile file) {
        SseEmitter emitter = new SseEmitter(60000L); // 60秒超时，因为流程更长
        
        CompletableFuture.runAsync(() -> {
            try {
                System.out.println("=== 开始完整文件处理流程 ===");
                System.out.println("问题: " + question);
                System.out.println("用户ID: " + userId);
                System.out.println("文件名: " + file.getOriginalFilename());
                System.out.println("文件大小: " + file.getSize() + " 字节");
                System.out.println("文件类型: " + file.getContentType());
                
                // 发送开始处理的消息
                emitter.send(SseEmitter.event()
                    .name("status")
                    .data("开始处理文件..."));
                
                // 步骤1: 上传文件到Coze平台
                System.out.println("步骤1: 上传文件到Coze平台");
                emitter.send(SseEmitter.event()
                    .name("status")
                    .data("正在上传文件到Coze平台..."));
                
                String fileId = cozeFileUploadService.uploadFileToCoze(file);
                System.out.println("✅ 文件上传成功，文件ID: " + fileId);
                
                emitter.send(SseEmitter.event()
                    .name("status")
                    .data("文件上传成功，正在检索文件内容..."));
                
                // 步骤2: 检索文件内容
                System.out.println("步骤2: 检索文件内容");
                String fileContent = cozeFileRetrieveService.retrieveFileContent(fileId);
                System.out.println("✅ 文件内容检索成功，内容长度: " + fileContent.length());
                
                emitter.send(SseEmitter.event()
                    .name("status")
                    .data("文件内容检索成功，正在发送给智能体处理..."));
                
                // 步骤3: 发送基于文件内容的对话请求
                System.out.println("步骤3: 发送基于文件内容的对话请求");
                cozeChatService.sendFileContentChatToCoze(question, fileContent, userId, emitter);
                
            } catch (Exception e) {
                System.err.println("❌ 完整文件处理流程失败: " + e.getMessage());
                e.printStackTrace();
                try {
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("文件处理失败: " + e.getMessage()));
                } catch (IOException ioException) {
                    System.err.println("发送错误信息失败: " + ioException.getMessage());
                }
                emitter.completeWithError(e);
            }
        });
        
        return emitter;
    }
}
